package com.ylwl.datacenterdemo.controller;

import com.ylwl.datacenterdemo.service.ExcelImportService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/excel")
@RequiredArgsConstructor
@Slf4j
public class ExcelImportController {
    
    private final ExcelImportService excelImportService;
    
    /**
     * 导入Excel文件到数据库（基于文件路径）
     * @param filePath Excel文件路径
     * @param tableName 可选的表名，默认使用文件名
     * @return 导入结果
     */
    @PostMapping("/import")
    public String importExcel(@RequestParam String filePath, 
                              @RequestParam(required = false) String tableName) {
        try {
            log.info("开始导入Excel文件: {}，目标表名: {}", filePath, tableName);
            excelImportService.importExcelToDatabase(filePath, tableName);
            return "Excel导入成功";
        } catch (Exception e) {
            log.error("Excel导入失败: ", e);
            return "Excel导入失败: " + e.getMessage();
        }
    }
    
    /**
     * 通过文件流导入Excel文件到数据库
     * @param file Excel文件
     * @param tableName 可选的表名，默认使用文件名
     * @return 导入结果
     */
    @PostMapping("/importByStream")
    public String importExcelByStream(@RequestParam("file") MultipartFile file,
                                      @RequestParam(required = false) String tableName) {
        try {
            if (file.isEmpty()) {
                return "上传的文件为空";
            }
            
            log.info("开始导入Excel文件: {}，目标表名: {}", file.getOriginalFilename(), tableName);
            excelImportService.importExcelByStream(file, tableName);
            return "Excel导入成功";
        } catch (Exception e) {
            log.error("Excel导入失败: ", e);
            return "Excel导入失败: " + e.getMessage();
        }
    }
}